package com.central.scheduler.service.registry;

import com.central.scheduler.common.utils.HeartBeat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Tindy
 * @date 2021/10/29
 * @describe
 */
public class HeartBeatTask implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(HeartBeatTask.class);

    private String heartBeatPath;
    private RegistryClient registryClient;
    private int workerWaitingTaskCount;
    private String serverType;
    private HeartBeat heartBeat;

    public HeartBeatTask(long startupTime,
                         double maxCpuloadAvg,
                         double reservedMemory,
                         String heartBeatPath,
                         String serverType,
                         RegistryClient registryClient) {
        this.heartBeatPath = heartBeatPath;
        this.registryClient = registryClient;
        this.serverType = serverType;
        this.heartBeat = new HeartBeat(startupTime, maxCpuloadAvg, reservedMemory);
    }

    public HeartBeatTask(long startupTime,
                         double maxCpuloadAvg,
                         double reservedMemory,
                         int hostWeight,
                         String heartBeatPath,
                         String serverType,
                         RegistryClient registryClient,
                         int workerThreadCount,
                         int workerWaitingTaskCount
    ) {
        this.heartBeatPath = heartBeatPath;
        this.registryClient = registryClient;
        this.workerWaitingTaskCount = workerWaitingTaskCount;
        this.serverType = serverType;
        this.heartBeat = new HeartBeat(startupTime, maxCpuloadAvg, reservedMemory, hostWeight, workerThreadCount);
    }

    public String getHeartBeatInfo() {
        return this.heartBeat.encodeHeartBeat();
    }

    @Override
    public void run() {
        try {
            // check dead or not in zookeeper
            if (registryClient.checkIsDeadServer(heartBeatPath, serverType)) {
//                registryClient.getStoppable().stop("i was judged to death, release resources and stop myself");
                return;
            }

            // update waiting task count
            heartBeat.setWorkerWaitingTaskCount(workerWaitingTaskCount);

            registryClient.update(heartBeatPath, heartBeat.encodeHeartBeat());

        } catch (Throwable ex) {
            logger.error("error write heartbeat info", ex);
        }
    }
}

